package com.guilang.localmusic;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ActivitySign extends AppCompatActivity implements View.OnClickListener {

    private String URL_LOGIN = "http://47.108.182.213/user/login";
    private String URL_REGIST = "http://47.108.182.213/user/insert";
    private Button login_sign_in, login_sign_up;
    private EditText login_tel, login_pwd;
    private String tel, pwd, msg, code, responseData, dataMsg, uId, lId;
    private CheckBox checkBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ActivityCollector.addActivity(this);

        Toolbar toolbar = findViewById(R.id.sign_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back);
        }
        //如果已经登陆则退出界面
        if(UserLoginINFO.getIsLogin()){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示")
                    .setIcon(R.drawable.music)
                    .setMessage("您已登陆！")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
        }
        InitLayout();

    }

    private void InitLayout() {
        //获取点击按钮
        login_sign_in = findViewById(R.id.login);
        login_sign_up = findViewById(R.id.regist);
        //获取Edit文本框
        login_tel = findViewById(R.id.login_tel);
        login_pwd = findViewById(R.id.login_pwd);
        //获取选择框
        checkBox = findViewById(R.id.remember_pwd);
        //设置点击事件
        login_sign_up.setOnClickListener(this);
        login_sign_in.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                //获取文本框内容
                getEdittext();
                sendRequestWithOkHttp(tel, pwd, URL_LOGIN);
                break;
            case R.id.regist:
                getEdittext();
                sendRequestWithOkHttp(tel, pwd, URL_REGIST);
            default:
                break;
        }

    }

    private void getEdittext() {
        tel = login_tel.getText().toString();
        pwd = login_pwd.getText().toString();
    }

    private void sendRequestWithOkHttp(String tel, String pwd, String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    //构建请求信息requestBody
                    RequestBody requestBody = new FormBody.Builder()
                            .add("tel", tel)
                            .add("usr", tel)
                            .add("pwd", pwd)
                            .add("appId", UserLoginINFO.getAppId())
                            .build();
                    //发起请求
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    //获取结果
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    showResponseData(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    //解析返回值的JSON
    private void parseJSONWithJsonObject(String responseData) {

        try {
            JSONObject object = new JSONObject(responseData);
            //解析标准返回值
            msg = object.getString("msg");
            code = object.getString("code");
            //解析登录返回data
            String data = object.optString("data");
            if (!data.isEmpty()) {
                JSONObject dataObject = new JSONObject(data);
                dataMsg = dataObject.optString("msg");
                lId = dataObject.optString("lId");
                uId = dataObject.optString("uId");
                //保存登陆信息
                saveUserLogin();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void saveUserLogin() {
        SharedPreferences preferences;
        SharedPreferences.Editor editor;
        preferences = PreferenceManager.getDefaultSharedPreferences(ActivitySign.this);
        editor = preferences.edit();
        //保存登录状态
        if (msg.equals("登录成功")) {
            UserLoginINFO.setIsLogin(true);
            UserLoginINFO.setTel(tel);
            UserLoginINFO.setUsr(tel);
            UserLoginINFO.setPwd(pwd);
            UserLoginINFO.setuId(uId);
            UserLoginINFO.setlId(lId);
            UserLoginINFO.setMsg(dataMsg);
            editor.putBoolean("isLogin", true);
            //是否记住密码
            if (checkBox.isChecked()) {
                editor.putBoolean("isRememberPwd", true);
                editor.putString("msg", UserLoginINFO.getMsg());
                editor.putString("usr", UserLoginINFO.getTel());
                editor.putString("tel", UserLoginINFO.getTel());
                editor.putString("uId", UserLoginINFO.getuId());
                editor.putString("lId", UserLoginINFO.getlId());
                editor.putString("pwd", UserLoginINFO.getPwd());
            } else {
                editor.clear();
            }
            editor.apply();
        }
    }

    //显示返回结果
    private void showResponseData(String responseData) {
        String regist_result;
        //先将结果json解析出来，msg，code
        parseJSONWithJsonObject(responseData);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //构建提示弹窗
                AlertDialog.Builder dialog = new AlertDialog.Builder(ActivitySign.this);
                dialog.setIcon(R.drawable.music)
                        .setTitle("提示")
                        .setMessage(responseData)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .create()
                        .show();
                TextView textView = findViewById(R.id.result);
                textView.setText(msg);
            }
        });
    }

    //设置Toolbar点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //恢复账号密码
        checkBox.setChecked(UserLoginINFO.getIsRememberPwd());
        if (UserLoginINFO.getIsRememberPwd()) {
            login_tel.setText(UserLoginINFO.getTel());
            login_pwd.setText(UserLoginINFO.getPwd());
            login_tel.setSelection(UserLoginINFO.getTel().length());
            login_pwd.setSelection(UserLoginINFO.getPwd().length());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}